import React, { useState, useEffect } from 'react';
import { 
  Typography, 
  Input, 
  Button, 
  Spin, 
  Alert, 
  Card, 
  Tabs, 
  List, 
  Tag, 
  Space,
  Row,
  Col,
  Select,
  Statistic
} from 'antd';
import {
  SendOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import { ShieldOutlined } from '../components/icons/IconComponents';
import puaService from '../api/puaService';
import contactsService from '../api/contactsService';
import PUACategoryInfo from '../components/pua/PUACategoryInfo';

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;
const { TabPane } = Tabs;
const { Option } = Select;

const PUADetectionPage = () => {
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [categories, setCategories] = useState([]);
  const [resources, setResources] = useState([]);
  const [patterns, setPatterns] = useState([]);
  const [activeTab, setActiveTab] = useState('detector');
  const [selectedCategory, setSelectedCategory] = useState('');
  const [selectedContact, setSelectedContact] = useState('');
  const [contacts, setContacts] = useState([]);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [historyResult, setHistoryResult] = useState(null);

  // 获取PUA模式类别和教育资源
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          setCategories([
            { id: 'gaslighting', name: '煤气灯效应', description: '让对方怀疑自己的感受和记忆' },
            { id: 'love_bombing', name: '爱情轰炸', description: '短时间内提供过度的关注和喜爱' },
            { id: 'negging', name: '负面评价', description: '通过批评降低对方的自尊心' },
            { id: 'isolation', name: '隔离控制', description: '试图切断对方与他人的联系' },
            { id: 'triangulation', name: '三角关系', description: '引入第三者制造不安全感' },
            { id: 'silent_treatment', name: '冷暴力', description: '通过沉默来惩罚对方' },
            { id: 'guilt_tripping', name: '罪恶感操纵', description: '制造罪恶感来控制对方行为' },
            { id: 'breadcrumbing', name: '面包屑喂养', description: '仅给予最低限度的关注来维持关系' }
          ]);
          
          setResources([
            {
              title: '识别情感操控',
              description: '学习如何识别常见的情感操控手段',
              url: 'https://example.com/emotional-manipulation',
              type: 'article'
            },
            {
              title: '设立健康边界',
              description: '关于如何在人际关系中设立健康边界的指南',
              url: 'https://example.com/healthy-boundaries',
              type: 'guide'
            },
            {
              title: 'PUA话术解析',
              description: '常见PUA话术的详细解析和应对方法',
              url: 'https://example.com/pua-analysis',
              type: 'video'
            },
            {
              title: '心理咨询资源',
              description: '提供专业心理支持的机构和资源',
              url: 'https://example.com/counseling-resources',
              type: 'resources'
            }
          ]);
          
          setContacts([
            { id: '1', name: '张三' },
            { id: '2', name: '李四' },
            { id: '3', name: '王五' }
          ]);
        }, 500);
        
        // 实际API调用示例：
        // const categoriesData = await puaService.getPUACategories();
        // const resourcesData = await puaService.getEducationalResources();
        // const contactsData = await contactsService.getContacts();
        // setCategories(categoriesData);
        // setResources(resourcesData);
        // setContacts(contactsData);
      } catch (error) {
        console.error('获取PUA数据失败:', error);
      }
    };

    fetchData();
  }, []);

  // 获取某类别的PUA模式
  useEffect(() => {
    if (selectedCategory) {
      const fetchPatterns = async () => {
        try {
          // 模拟数据 - 实际应用中应使用API
          setTimeout(() => {
            setPatterns([
              {
                id: 1,
                pattern: '你太敏感了',
                category: 'gaslighting',
                description: '这是一种常见的否定对方感受的煤气灯效应话术',
                severity: 0.7,
                examples: ['你想太多了', '你总是对这种事情小题大做'],
                response_templates: ['我相信我的感受是真实的', '我希望你能尊重我的感受']
              },
              {
                id: 2,
                pattern: '不是我的意思',
                category: 'gaslighting',
                description: '通过否认自己的言行让对方怀疑记忆',
                severity: 0.6,
                examples: ['我从来没说过那种话', '你记错了'],
                response_templates: ['我清楚地记得这件事', '我们可以尊重彼此的观点']
              }
            ]);
          }, 300);
          
          // 实际API调用示例：
          // const patternsData = await puaService.getPUAPatterns(selectedCategory);
          // setPatterns(patternsData);
        } catch (error) {
          console.error('获取PUA模式失败:', error);
        }
      };

      fetchPatterns();
    } else {
      setPatterns([]);
    }
  }, [selectedCategory]);

  // 检测文本中的PUA内容
  const handleDetect = async () => {
    if (!content.trim()) return;
    
    setLoading(true);
    setResult(null);
    
    try {
      // 模拟API调用
      setTimeout(() => {
        const mockResult = {
          is_pua: content.toLowerCase().includes('敏感') || content.toLowerCase().includes('想太多'),
          score: content.toLowerCase().includes('敏感') ? 0.75 : 0.4,
          risk_level: content.toLowerCase().includes('敏感') ? 'medium' : 'low',
          detected_patterns: content.toLowerCase().includes('敏感') ? [
            {
              category: 'gaslighting',
              description: '煤气灯效应，让对方怀疑自己的感受和判断',
              severity: 0.8
            }
          ] : [],
          explanation: content.toLowerCase().includes('敏感') ? 
            '该文本使用了煤气灯效应技巧，试图让对方怀疑自己的判断。' : 
            '未检测到明显的PUA内容，但建议保持警惕。',
          response_suggestions: content.toLowerCase().includes('敏感') ? [
            '我相信我的感受是真实的，这不是我想太多。',
            '请不要否认我的感受，我们应该相互尊重。',
            '我需要你尊重我的想法和感受。'
          ] : []
        };
        
        setResult(mockResult);
        setLoading(false);
      }, 1000);
      
      // 实际API调用示例：
      // const detectionResult = await puaService.detectPUA(content);
      // setResult(detectionResult);
    } catch (error) {
      console.error('PUA检测失败:', error);
      setLoading(false);
    }
  };

  // 分析历史聊天记录
  const handleHistoryAnalysis = async () => {
    if (!selectedContact) return;
    
    setHistoryLoading(true);
    setHistoryResult(null);
    
    try {
      // 模拟API调用
      setTimeout(() => {
        const mockHistoryResult = {
          total_messages: 78,
          pua_messages: 12,
          pua_ratio: 0.15,
          risk_level: 'medium',
          common_patterns: [
            {
              category: 'gaslighting',
              count: 5
            },
            {
              category: 'guilt_tripping',
              count: 4
            }
          ],
          trend: 'increasing',
          recommendation: '该对话的PUA风险等级为medium。主要表现为: 煤气灯效应(让你怀疑自己的判断), 罪恶感操纵(制造罪恶感控制你的行为)。建议在回复时注意保护自己的边界，不要被情绪操控。'
        };
        
        setHistoryResult(mockHistoryResult);
        setHistoryLoading(false);
      }, 1500);
      
      // 实际API调用示例：
      // const analysisResult = await puaService.analyzeHistory(selectedContact, 100);
      // setHistoryResult(analysisResult);
    } catch (error) {
      console.error('历史分析失败:', error);
      setHistoryLoading(false);
    }
  };

  // 根据风险等级获取颜色
  const getRiskColor = (level) => {
    switch(level) {
      case 'high': return 'red';
      case 'medium': return 'orange';
      case 'low': return 'green';
      default: return 'default';
    }
  };

  // 根据风险等级获取图标
  const getRiskIcon = (level) => {
    switch(level) {
      case 'high': return <WarningOutlined />;
      case 'medium': return <InfoCircleOutlined />;
      case 'low': return <CheckCircleOutlined />;
      default: return null;
    }
  };

  return (
    <div>
      <Title level={2}>
        <Space>
          <ShieldOutlined />
          PUA检测与防护
        </Space>
      </Title>
      <Paragraph>
        分析聊天内容中可能存在的PUA行为，获取防护建议和应对策略。
      </Paragraph>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="文本检测" key="detector">
          <Card>
            <TextArea 
              rows={6} 
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder="输入需要检测的聊天内容..."
              maxLength={500}
              showCount
            />
            <div style={{ marginTop: 16, textAlign: 'right' }}>
              <Button 
                type="primary" 
                icon={<SendOutlined />} 
                onClick={handleDetect}
                loading={loading}
                disabled={!content.trim()}
              >
                检测
              </Button>
            </div>

            {loading && <div style={{ textAlign: 'center', margin: '20px 0' }}><Spin /></div>}

            {result && (
              <div style={{ marginTop: 20 }}>
                <Alert
                  message={
                    result.is_pua 
                      ? `检测到PUA内容 (风险等级: ${result.risk_level})` 
                      : "未检测到明显PUA内容"
                  }
                  description={result.explanation}
                  type={result.is_pua ? (result.risk_level === 'high' ? 'error' : 'warning') : 'success'}
                  showIcon
                />

                {result.detected_patterns && result.detected_patterns.length > 0 && (
                  <div style={{ marginTop: 16 }}>
                    <Text strong>检测到的PUA模式:</Text>
                    <div style={{ marginTop: 8 }}>
                      {result.detected_patterns.map((pattern, index) => (
                        <Tag color={getRiskColor(pattern.severity > 0.7 ? 'high' : pattern.severity > 0.4 ? 'medium' : 'low')} key={index} style={{ marginBottom: 8 }}>
                          {pattern.category} - {pattern.description}
                        </Tag>
                      ))}
                    </div>
                  </div>
                )}

                {result.response_suggestions && result.response_suggestions.length > 0 && (
                  <div style={{ marginTop: 16 }}>
                    <Text strong>应对建议:</Text>
                    <List
                      style={{ marginTop: 8 }}
                      size="small"
                      bordered
                      dataSource={result.response_suggestions}
                      renderItem={(item, index) => (
                        <List.Item>
                          <Text>{index + 1}. {item}</Text>
                        </List.Item>
                      )}
                    />
                  </div>
                )}
              </div>
            )}
          </Card>
        </TabPane>

        <TabPane tab="聊天历史分析" key="history">
          <Card>
            <Row gutter={16}>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>选择联系人:</Text>
                  <Select 
                    style={{ width: '100%', marginTop: 8 }} 
                    placeholder="选择要分析的联系人"
                    value={selectedContact}
                    onChange={setSelectedContact}
                  >
                    {contacts.map(contact => (
                      <Option key={contact.id} value={contact.id}>{contact.name}</Option>
                    ))}
                  </Select>
                </div>
              </Col>
              <Col span={12} style={{ display: 'flex', alignItems: 'flex-end' }}>
                <Button 
                  type="primary" 
                  onClick={handleHistoryAnalysis}
                  loading={historyLoading}
                  disabled={!selectedContact}
                  style={{ marginBottom: 16 }}
                >
                  分析
                </Button>
              </Col>
            </Row>

            {historyLoading && <div style={{ textAlign: 'center', margin: '20px 0' }}><Spin /></div>}

            {historyResult && (
              <div>
                <Alert
                  message={`PUA风险评估: ${historyResult.risk_level}`}
                  description={historyResult.recommendation}
                  type={historyResult.risk_level === 'high' ? 'error' : historyResult.risk_level === 'medium' ? 'warning' : 'info'}
                  showIcon
                  icon={getRiskIcon(historyResult.risk_level)}
                />

                <Row gutter={16} style={{ marginTop: 16 }}>
                  <Col span={8}>
                    <Card size="small">
                      <Statistic 
                        title="总消息数" 
                        value={historyResult.total_messages} 
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card size="small">
                      <Statistic 
                        title="PUA消息数" 
                        value={historyResult.pua_messages} 
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card size="small">
                      <Statistic 
                        title="PUA比例" 
                        value={historyResult.pua_ratio * 100} 
                        suffix="%" 
                        precision={1}
                      />
                    </Card>
                  </Col>
                </Row>

                <div style={{ marginTop: 16 }}>
                  <Text strong>常见PUA模式:</Text>
                  <div style={{ marginTop: 8 }}>
                    {historyResult.common_patterns.map((pattern, index) => (
                      <Tag color="red" key={index} style={{ marginBottom: 8 }}>
                        {pattern.category} (出现{pattern.count}次)
                      </Tag>
                    ))}
                  </div>
                </div>

                <div style={{ marginTop: 16 }}>
                  <Text strong>趋势: </Text>
                  <Tag color={historyResult.trend === 'increasing' ? 'red' : 'green'}>
                    {historyResult.trend === 'increasing' ? '增加' : '减少'}
                  </Tag>
                </div>
              </div>
            )}
          </Card>
        </TabPane>

        <TabPane tab="PUA知识库" key="knowledge">
          <Row gutter={16}>
            <Col span={12}>
              <Card title="PUA模式类别" style={{ marginBottom: 16 }}>
                <Select 
                  style={{ width: '100%', marginBottom: 16 }} 
                  placeholder="选择PUA类别查看详情"
                  value={selectedCategory}
                  onChange={setSelectedCategory}
                  allowClear
                >
                  {categories.map(category => (
                    <Option key={category.id} value={category.id}>{category.name}</Option>
                  ))}
                </Select>

                <List
                  itemLayout="horizontal"
                  dataSource={categories}
                  renderItem={category => (
                    <List.Item 
                      actions={[
                        <Button 
                          type={selectedCategory === category.id ? "primary" : "text"} 
                          size="small" 
                          onClick={() => setSelectedCategory(category.id)}
                        >
                          查看详情
                        </Button>
                      ]}
                    >
                      <List.Item.Meta
                        title={category.name}
                        description={category.description}
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>

            <Col span={12}>
              {selectedCategory ? (
                <PUACategoryInfo categoryId={selectedCategory} showExamples={true} />
              ) : (
                <Card title="PUA模式详情" style={{ marginBottom: 16, height: "100%" }}>
                  <div style={{ textAlign: 'center', padding: '20px 0', color: '#999' }}>
                    <InfoCircleOutlined style={{ fontSize: 48, color: '#ddd', marginBottom: 16 }} />
                    <p>请从左侧选择一个PUA类别查看详细信息</p>
                  </div>
                </Card>
              )}
            </Col>
          </Row>

          <Card title="防护教育资源">
            <List
              itemLayout="horizontal"
              dataSource={resources}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    title={<a href={item.url} target="_blank" rel="noopener noreferrer">{item.title}</a>}
                    description={item.description}
                  />
                  <Tag color="blue">{item.type}</Tag>
                </List.Item>
              )}
            />
          </Card>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default PUADetectionPage; 